<?php

namespace handle\message\lib\manage\lib;

use handle\message\lib\manage\traits\Observer;

class Room
{
    use Observer;

    /**
     * 房间ID编号
     * @var string
     */
    private string $room_id;

    /**
     * @var int
     * @params {
     *      0: 待开始,
     *      1: 开始游戏,
     *      2: 结束游戏,
     * }
     */
    private int $status;

    /**
     * 胜负状态
     * @var int
     * @params {
     *      1: 白棋胜利,
     *      2: 黑棋胜利,
     *      3: 平局,
     *      4: 逃跑,
     *      6: 系统级-平局
     * }
     */
    private int $outcome;

    /**
     * 玩家信息类
     * @var array
     */
    private array $playerInfo = [];

    /**
     * 初始化房间
     * @param string $room_id 房间ID编号
     */
    public function __construct(string $room_id)
    {
        $this->room_id = $room_id;
        $this->status = 0;
    }

    /**
     * 重置房间
     * @return void
     */
    public function init(){
        $this->status = 0;
        $this->outcome = 0;
        $this->notifyManage();
    }

    /**
     * 获取房间ID
     * @return string
     */
    public function getRoomId(): string
    {
        return $this->room_id;
    }

    /**
     * 添加玩家
     * @param int $uid 玩家ID
     * @return void
     */
    public function addPlayer(int $uid)
    {
        count($this->playerInfo) < 2 and ($this->playerInfo[] = $uid);
        $this->notifyManage();
    }

    /**
     * 获取玩家信息
     * @return array
     */
    public function getPlayerInfo(): array
    {
        return $this->playerInfo;
    }

    /**
     * 退出房间
     * @param int $uid
     * @return void
     */
    public function exitRoom(int $uid)
    {
        if (($key = array_search($uid, $this->playerInfo)) !== false) {
            unset($this->playerInfo[$key]);
            $this->notifyManage();
        }
    }

    /**
     * 判断房间是否还有人
     * @return bool
     */
    public function hasAnyoneElse(): bool
    {
        return count($this->getPlayerInfo()) > 0;
    }

    /**
     * 判断玩家是否在房间中
     * @param int $uid
     * @return bool
     */
    public function checkMyselfInRoom(int $uid): bool
    {
        return in_array($uid, $this->getPlayerInfo());
    }

    /**
     * 开始游戏
     * @return void
     */
    public function startGame(){
        $this->status = 1;
        $this->notifyManage();
    }

    /**
     * 结束游戏
     * @return void
     */
    public function endGame(){
        $this->status = 2;
        $this->notifyManage();
    }

    /**
     * 获取房间游戏状态
     * @return int
     */
    public function getStatus(): int
    {
        return $this->status;
    }

    /**
     * 设置胜负状态
     * @param int $outcome
     * @return void
     */
    public function setOutcome(int $outcome){
        $this->status = 2;
        $this->outcome = $outcome;
        $this->notifyManage();
    }

    /**
     * 获取胜负状态
     * @return int
     */
    public function getOutcome(): int
    {
        return $this->outcome;
    }

}